<?php

namespace app\admin\controller\user;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use app\admin\model\org\Orgcate;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Visit extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $searchFields = 'user.id,user.username,user.nickname';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->view->assign('org_cate_id', ORG_CATE_ID);
        $orgcateModel = new \app\admin\model\org\Orgcate;
        $this->orgcatelist = $orgcateModel->getOrgCateList();

        $usergroup = new \app\admin\model\UserGroup;
        $grouplist = collection($usergroup->select())->toArray();
        $this->usergroup = [];
        foreach($grouplist as $v){
            $this->usergroup[$v['id']] = $v['name'];
        }
        $orgGradeModel = new \app\admin\model\org\Orggrade;
        $this->gradeList = $orgGradeModel->getGradeList();

        $orgGradeUserModel = model('OrgGradeUser');

        $this->view->assign('genderList', $this->model->getGenderList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign('orgcatelist', $this->orgcatelist);
        $this->view->assign('usergroup', $this->usergroup);
        $this->view->assign('gradeList', $this->gradeList );
        $this->view->assign('typeList', $this->model->getTypeList() );
    }

    /**
     * 查看
     */
    public function index() 
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2 = $this->getSelfDataWhere('user.org_cate_id');
            $total = $this->model
                ->with('group')
                ->where($where)
                ->where($where2)
                ->where(['user.user_type'=>2])
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where($where2)
                ->where(['user.user_type'=>2])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $grade_user_id = [];
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
                $list[$k]['org_cate_id'] = isset($this->orgcatelist[$v['org_cate_id']])?$this->orgcatelist[$v['org_cate_id']]:'总平台';
                $grade_user_id[] = $v['id'];
            }
            if($grade_user_id){
                $orgGradeUserModel = model('OrgGradeUser');
                $gradeUserList = $orgGradeUserModel->where(array('user_id' => array('in', $grade_user_id)))->column('org_grade_id', 'user_id');
                foreach($list as $k => $v){
                    $list[$k]['org_grade_id'] = isset($gradeUserList[$v['id']]) ? $gradeUserList[$v['id']]  : 0;
                }
            }
            foreach ($list as $k => $v) {
                $list[$k]['org_grade_name'] = $v['org_grade_id'] == 0 ? '' : $this->gradeList[$v['org_grade_id']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add(){
        if($this->request->isPost()){
            $params = $this->request->post("row/a", [], 'strip_tags');
            if($params){
                Db::startTrans();
                try{
                    $params['password'] = md5(md5($params['password']));
                    $grade_id = $params['org_grade_id'];
                    unset($params['org_grade_id']);
                    $params['org_cate_id'] = ORG_CATE_ID;
                    $user_id = $this->model->insertGetId($params);
                    if($user_id === false){
                        $this->error($this->model->getError());
                    }
                    if($grade_id != 0){
                        $grade_user['user_id'] = $user_id;
                        $grade_user['org_grade_id'] = $grade_id;
                        model('OrgGradeUser')->insert($grade_user);
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();    
            }
            $this->error();
            
        }   

        $this->view->assign('orgcatList', $this->orgcatelist);
        $this->view->assign('groupList', $this->usergroup);

        return $this->view->fetch();

    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $org_grade_info = model('OrgGradeUser')->where('user_id',  $row['id'])->find();
        $org_grade_id = isset($org_grade_info['org_grade_id'])?$org_grade_info['org_grade_id']:0;
        $this->view->assign('org_grade_id', $org_grade_id);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $new_grade_id = $params['org_grade_id'];
                unset($params['org_grade_id']);
                Db::startTrans();
                try{
                    $result = $row->save($params);
                    if($new_grade_id != 0){
                        if($org_grade_info){
                            if($new_grade_id != $org_grade_info['org_grade_id']){
                                $grade_user['org_grade_id'] = $new_grade_id;
                                model('OrgGradeUser')->where('id', $org_grade_info['id'])->update($grade_user);
                            }
                        }else{
                            $grade_user['user_id'] = $row['id'];
                            $grade_user['org_grade_id'] = $new_grade_id;
                            model('OrgGradeUser')->insert($grade_user);
                        }
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('操作失败'));
                }
            }
            $this->error(__('操作失败', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
